<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


//无限极分类 生成树形数组
function make_tree($list,$root=0){
    $tree=array();
    $packData=array();
    //将所有的分类id作为数组key
    foreach ($list as $k=>$v) {
        $packData[$v['id']] = $v;
    }
    //利用引用，将每个分类添加到父类child数组中，这样一次遍历即可形成树形结构。
    foreach ($packData as $key =>$val){
        if($val['pid']==$root){//代表跟节点
            $tree[] = &$packData[$key];
        }else{
            //找到其父类
            $packData[$val['pid']]['child'][] = &$packData[$key];
        }
    }
    return $tree;
}

/***
* 获取客户端ip
**/
function get_ip(){
    //判断服务器是否允许$_SERVER
    if(isset($_SERVER)){    
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $realip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }elseif(isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            $realip = $_SERVER['REMOTE_ADDR'];
        }
    }else{
        //不允许就使用getenv获取  
        if(getenv("HTTP_X_FORWARDED_FOR")){
              $realip = getenv( "HTTP_X_FORWARDED_FOR");
        }elseif(getenv("HTTP_CLIENT_IP")) {
              $realip = getenv("HTTP_CLIENT_IP");
        }else{
              $realip = getenv("REMOTE_ADDR");
        }
    }

    return $realip;
}

/**
* 自定义分页
**/
function get_page(&$m, $where = array(), $page_size = 1){
    $m1=clone $m;//浅复制一个模型
    $list = $m->where($where)->paginate($page_size,false, [
        'query' => request()->param(),
    ]);
    $m=$m1;//为保持在为定的连惯操作，浅复制一个模型
   
    $p = empty($_GET['page']) ? 1 : intval($_GET['page']);
    //$total = ceil($count/$page_size);
    $start = ($p-1)*$page_size;
    $limit = $start.",".$page_size;
    
    $page = $list->render();

    $data = $m->where($where)
        ->limit($limit)
        ->select();
    
    
    return array('list'=>$data, 'page'=>$page);
}



/**
* 创建验证码
**/
function verify($len=4,$width=100,$height=40,$font_size=20,$font_type="arial.ttf"){
    $verify = get_rand_str($len);
    //session_start();
    $_SESSION['verify'] = $verify;
    
    //session('verify', $verify);
    $len = strlen($verify);
    $img = imagecreatetruecolor($width, $height); 
    // 定义要用到的颜色
    $back_color = imagecolorallocate($img, 235, 236, 237);
    $boder_color = imagecolorallocate($img, 118, 151, 199);

    // 画背景
    imagefilledrectangle($img, 0, 0, $width, $height, $back_color); 
    // 画边框
    imagerectangle($img, 0, 0, $width-1, $height-1, $boder_color);
    // 画干扰线
    for($i = 0;$i < 5;$i++) {
        $line_color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        imageline($img, 0, mt_rand(0,$height), $width, mt_rand(0,$height), $line_color);
    } 
    // 画干扰点
    for($i = 0;$i < 100;$i++) {
        $point_color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $point_color);
    }
    
    if(!file_exists($font_type)){
        $font_type = APP_PATH.$font_type;
    }
    //写数据
    for($i=0; $i<$len; $i++){
        $code = substr($verify,$i,1);
        $text_color = imagecolorallocate($img, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120)); 
        imagefttext($img,$font_size,mt_rand(5,50),($width-$font_size*$len)/2+($i*$font_size),($font_size+$height)/2,$text_color,$font_type,$code);
    }
    //imagefttext($img,$font_size,0,($width-$font_size*$len)/2,($font_size+$height)/2,$text_color,$font_type,$verify);
    header("Content-type: image/png");
    imagepng($img);
    imagedestroy($img);
}

/**
* 获取随机字符串
**/
function get_rand_str($len){
    $str = "1234567890asdfghjklqwertyuiopzxcvbnm";
    //$str = "123456789012345678901234567890";
    return substr(str_shuffle($str),0,$len);
}

//随机字符串
function nocstr($len,$type=false){
    $str = "1234567890asdfghjklqwertyuiopzxcvbnm";
    if($type){
        $str = "123456789012345678901234567890";
    }
    return substr(str_shuffle($str),0,$len);
}


/**
 * 创建密码
 * @param $password: 密码
 * @return string
 */
function createPassword($password){
    $key = 'FF7E772C8B01B8D02F49946D39E786F0';
    $password = sha1($password . $key);
    $password = strrev(sha1($password . $key));
    $password = md5($password);
    $password = strtoupper($password);
    return $password;
}


/**
 * 创建token
 * @param $id: 用户id
 * @return string
 */
function createToken($id){
    $token = uniqid();
    $token = $token . $id;
    $token = md5($token);
    $token = str_shuffle(strtoupper($token));
    return $token;
}

function createTmpToken($id){
    $token = uniqid();
    $token = $token . $id;
    $token = md5($token);
    $token = substr(str_shuffle(strtoupper($token)), 0, 30);
    return $token;
}

/**
* 根据概率获取奖项
*/
function getRand($proArr) { 
    $result = ''; 

    //概率数组的总概率精度 
    $proSum = array_sum($proArr); //计算数组中元素的和
    //概率数组循环 
    foreach ($proArr as $key => $proCur) { 
        $randNum = mt_rand(1, $proSum); 
        if ($randNum <= $proCur) { //如果这个随机数小于等于数组中的一个元素，则返回数组的下标
            $result = $key; 
            break; 
        } else { 
            $proSum -= $proCur; 
        } 
    } 

    unset ($proArr); 

    return $result; 
}

/**
 * 接口操作成功
 * @param array $data
 * @param string $message
 * @param int $code
 * @return \think\response\Json
 */
function apiSuccess($data = [], $message = 'ok', $code = 200)
{
    if(isset($data['current_page'])){
        $data['total'] = (int)$data['total'];
        $data['per_page'] = (int)$data['per_page'];
        $data['current_page'] = (int)$data['current_page'];
        $data['per_page'] = (int)$data['per_page'];
        $data['last_page'] = (int)$data['last_page'];
    }
    $data === '' ? $data=[]:$data;
    $r = [
        'code' => $code,
        'msg' => $message,
        'data' => $data
    ];
    //var_dump($r);die;
    return json_encode($r);
}


/**
 * 接口操作失败
 * @param string $message
 * @param int $code
 * @return \think\response\Json
 */
function apiError($message = '操作失败', $code = 201)
{
    $r = [
        'code' => $code,
        'msg' => $message,
        'data' => []
    ];
    return json_encode($r);
}

/**
 * 操作成功
 * @param array $data
 * @param string $message
 * @param int $code
 * @return \think\response\Json
 */
function outputSuccess($data = [], $message = 'ok', $code = 0)
{
    if(isset($data['current_page'])){
        $data['total'] = (int)$data['total'];
        $data['per_page'] = (int)$data['per_page'];
        $data['current_page'] = (int)$data['current_page'];
        $data['per_page'] = (int)$data['per_page'];
        $data['last_page'] = (int)$data['last_page'];
    }
    $data === '' ? $data=[]:$data;
    $r = [
        'code' => $code,
        'msg' => $message,
        'data' => $data
    ];
    return json_encode($r);
}


/**
 * 操作失败
 * @param string $message
 * @param int $code
 * @return \think\response\Json
 */
function outputError($message = '操作失败', $code = 1)
{
    $r = [
        'code' => $code,
        'msg' => $message,
        'data' => []
    ];
    return json_encode($r);
}
/**
 * 验证AppStore内付
 * @param  string $receipt_data 付款后凭证
 * @return array                验证是否成功
 */
function validate_apple_pay($receipt_data){
    /**
     * 21000 App Store不能读取你提供的JSON对象
     * 21002 receipt-data域的数据有问题
     * 21003 receipt无法通过验证
     * 21004 提供的shared secret不匹配你账号中的shared secret
     * 21005 receipt服务器当前不可用
     * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
     * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
     * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
     */
    function acurl($receipt_data, $sandbox=0){
        //小票信息
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        //$POSTFIELDS = json_encode($POSTFIELDS);
        $POSTFIELDS = '{"receipt-data": "'.$receipt_data.'"}';
        //正式购买地址 沙盒购买地址
        $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
        $url = $sandbox ? $url_sandbox : $url_buy;
        //简单的curl
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    // 验证参数
    if (strlen($receipt_data)<20){
        $result=array(
            'status'=>false,
            'message'=>'非法参数'
        );
        return $result;
    }
    // 请求验证
    $html = acurl($receipt_data);
    $data = json_decode($html,true);

    // 如果是沙盒数据 则验证沙盒模式
    if($data['status']=='21007'){
        // 请求验证
        $html = acurl($receipt_data, 1);
        $data = json_decode($html,true);
        $data['sandbox'] = '1';
    }

    if (isset($_GET['debug'])) {
        exit(json_encode($data));
    }

    // 判断是否购买成功
    if(intval($data['status'])===0){
        $result=array(
            'status'=>true,
            'message'=>'购买成功'
        );
    }else{
        $result=array(
            'status'=>false,
            'message'=>'购买失败 status:'.$data['status']
        );
    }
    return $result;
}

//数组转对象
function array2object($array) {
  if (is_array($array)) {
    $obj = new StdClass();
    foreach ($array as $key => $val){
      $obj->$key = $val;
    }
  }
  else { $obj = $array; }
  return $obj;
}
 

 
//对象转属组
function object2array($object) {
  if (is_object($object)) {
    foreach ($object as $key => $value) {
      $array[$key] = $value;
    }
  }
  else {
    $array = $object;
  }
  return $array;
}


//图片上传
function upload($file, $dir = 'appimg'){
    
    if($file['error'] != 0){
        return false;
    }
    $file_size = $file['size'];
    $file_max_size = 1024*1024*10;//1M
    $tmp_file = $file['tmp_name'];
    $file_name = $file['name'];
    
    $file_info = getimagesize($tmp_file);//获取文件信息
    $type = $file_info['mime'];

    //验证文件类型
    $type_arr = array('image/jpeg','image/jpg','image/png','image/gif');
    if(!in_array($type,$type_arr)){
        //die('文件类型不存在，请上传....');
        return array('code'=>201, 'msg'=>'文件类型不存在', 'des'=>'');
    }
    
    //验证文件大小
    if($file_size > $file_max_size || $file_size <=0){
        //die('请上传合法大小的文件');
        return array('code'=>202, 'msg'=>'请上传合法大小的文件', 'des'=>'');
    }
    
    //验证是否是post上传的
    if(!is_uploaded_file($tmp_file)){
        //die('文件上传失败');
        return array('code'=>203, 'msg'=>'文件上传失败', 'des'=>'');
    }
    $type = explode('/',$type);
    $new_name = date('YmdHis').rand(10000,99999);
    $dir = $dir.'/'.date("Ymd").'/';
    
    
    if(!file_exists($dir)){
        mkdir($dir,0777,true);
    }

    $destination = $dir.$new_name.'.'.$type[1];
    //$destination = $dir.$new_name.'.'.'png';
    //var_dump($destination);die;
    
    //讲本地文件移动到服务器上
    $ret = move_uploaded_file($tmp_file,$destination);
    if($ret){
        return array('code'=>200, 'msg'=>'文件上传成功', 'des'=>$destination);
        //return $destination;
    }else{
        return array('code'=>204, 'msg'=>'文件上传失败', 'des'=>'');
    }
}


//文件上传
function upload_file($dir = 'appimg'){
    $file = $_FILES['file'];//得到传输的数据
    if($file['error'] != 0){
        return false;
    }
    
    $file_size = $file['size'];
    $file_max_size = 1024*1024*20;//1M
    $tmp_file = $file['tmp_name'];
    $file_name = $file['name'];
    
    $ext = substr($file_name, -3,3);
    $type = $file['type'];
    //验证文件类型
    $type_arr = array('application/octet-stream');
    if(!in_array($type,$type_arr)){
        //die('文件类型不存在，请上传....');
        return array('code'=>201, 'msg'=>'文件类型不存在', 'des'=>'');
    }
    
    //验证文件大小
    if($file_size > $file_max_size || $file_size <=0){
        //die('请上传合法大小的文件');
        return array('code'=>202, 'msg'=>'请上传合法大小的文件', 'des'=>'');
    }
    
    //验证是否是post上传的
    if(!is_uploaded_file($tmp_file)){
        return array('code'=>203, 'msg'=>'文件上传失败', 'des'=>'');
        //die('文件上传失败');
    }
    $type = explode('/',$type);
    $new_name = date('YmdHis').rand(10000,99999);
    $dir = $dir.'/'.date("Ymd").'/';
    
    
    if(!file_exists($dir)){
        mkdir($dir,0777,true);
    }

    $destination = $dir.$new_name.'.'.$ext;
    
    //讲本地文件移动到服务器上
    $ret = move_uploaded_file($tmp_file,$destination);
    if($ret){
        return array('code'=>200, 'msg'=>'文件上传失败', 'des'=>$destination);
    }else{
        return array('code'=>204, 'msg'=>'文件上传失败', 'des'=>'');
    }
}

/**
 * [将Base64图片转换为本地图片并保存]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://blog.iinu.com.cn
 * @param  [Base64] $base64_image_content [要保存的Base64]
 * @param  [目录] $path [要保存的路径]
 */
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        //var_dump($type);die;
        $allow = array('jpg','jpeg','png','gif');
        if(!in_array($type, $allow)){
            return false;
        }
        $info = file_get_contents($base64_image_content);
        $len = strlen($info);
        //var_dump($len);die;
        $max_size = 1024*1024*1; //1M
        if($len > $max_size){
            return false;
        }
        $new_file = $path."/".date('Ymd',time())."/";
        //var_dump($new_file);die;
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0755,true);
        }
        $new_file = $new_file.time().".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return $new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

function uploads($file, $dir="image/img"){
    $file_size = $file['size'];
    $file_max_size = 1024*1024*10;//10M
    $tmp_file = $file['tmp_name'];
    $file_name = $file['name'];

    $file_info = getimagesize($tmp_file);//获取文件信息
    $type = $file_info['mime'];

    //验证文件类型
    $type_arr = array('image/jpeg','image/jpg','image/png','image/gif');
    if(!in_array($type,$type_arr)){
        //die('文件类型不存在，请上传....');
        return false;
    }
    
    //验证文件大小
    if($file_size > $file_max_size || $file_size <=0){
        //die('请上传合法大小的文件');
        return false;
    }
    
    //验证是否是post上传的
    if(!is_uploaded_file($tmp_file)){
        //die('文件上传失败');
        return false;
    }
    $type = explode('/',$type);
    $new_name = date('YmdHis').rand(10000,99999);
    $dir = $dir.'/'.date("Ymd").'/';
    
    
    if(!file_exists($dir)){
        mkdir($dir,0777,true);
    }

    $destination = $dir.$new_name.'.'.$type[1];
    //var_dump($destination);die;
    
    //讲本地文件移动到服务器上
    $ret = move_uploaded_file($tmp_file,$destination);
    if($ret){
        return $destination;//返回图片存储路径
    }else{
        return false;
    }
}


/*
图片等比例压缩
*/
function thumb($img_path,$thumb_dir="./thumb",$height=300,$width=300){
    date_default_timezone_set('PRC');
    
    if(!file_exists($img_path)){
        return false;
    }
    /*获取图片信息*/
    $img_info = getimagesize($img_path);
    //var_dump($img_info);die;
    $img_w = $img_info[0];//图片宽度 400 100
    $img_h = $img_info[1];//图片高度 300 100
    if($img_w < $width){
        return $img_path;
    }
    $img_type = explode('/',$img_info['mime']);
    $img_type = $img_type[1];
     /*获取图片信息*/
    /*获取缩放比例，等比例压缩*/
    $ratio_h = $height/$img_h;
    $ratio_w = $width/$img_w;

    if($ratio_h < $ratio_w ){
        $ratio = $ratio_h;
    }else{
        $ratio = $ratio_w;
    }
    /*获取缩放比例*/
    
    //$ratio = 0.5;//缩放比例
    $new_width = $img_w * $ratio;//优化缩放比例
    $new_height = $img_h * $ratio;
    $image_wp=imagecreatetruecolor($new_width, $new_height);//创建画布 
    
    $thumb_dir = $thumb_dir."/".date("Ymd").'/';//压缩文件存放目录
    if(!file_exists($thumb_dir)){
        mkdir($thumb_dir, 0755, true);
    }
    //$imgdst = $thumb_dir.date("YmdHis").rand(1000,9999).'.'.$img_type;//存放路径$imgdst = 'img/'.date("YmdHis").rand(1000,9999).'.'.$img_type;//存放路径
    $imgdst = $thumb_dir.date("YmdHis").rand(1000,9999).'.'.'png';//存放路径$imgdst = 'img/'.date("YmdHis").rand(1000,9999).'.'.$img_type;//存放路径

    switch($img_type){
        case 'jpg':
        case 'jpeg':
            $image = imagecreatefromjpeg($img_path);//新图片
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $img_w , $img_h);//拷贝文件
            imagejpeg($image_wp, $imgdst); //保存到指定路劲
            break;  
        case 'png':
            $image = imagecreatefrompng($img_path);//新图片
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $img_w , $img_h);//拷贝文件
            imagepng($image_wp, $imgdst); //保存到指定路劲
            break;
        case 'gif':
            $image = imagecreatefromgif($img_path);//新图片
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $img_w , $img_h);//拷贝文件
            imagegif($image_wp, $imgdst); //保存到指定路劲
            break;
    }
    imagedestroy($image_wp);
    return $imgdst;
}

function rand_name(){
    $nicheng_tou=array('快乐的','冷静的','醉熏的','潇洒的','糊涂的','积极的','冷酷的','深情的','粗暴的','温柔的','可爱的','愉快的','义气的','认真的','威武的','帅气的','传统的','潇洒的','漂亮的','自然的','专一的','听话的','昏睡的','狂野的','等待的','搞怪的','幽默的','魁梧的','活泼的','开心的','高兴的','超帅的','留胡子的','坦率的','直率的','轻松的','痴情的','完美的','精明的','无聊的','有魅力的','丰富的','繁荣的','饱满的','炙热的','暴躁的','碧蓝的','俊逸的','英勇的','健忘的','故意的','无心的','土豪的','朴实的','兴奋的','幸福的','淡定的','不安的','阔达的','孤独的','独特的','疯狂的','时尚的','落后的','风趣的','忧伤的','大胆的','爱笑的','矮小的','健康的','合适的','玩命的','沉默的','斯文的','香蕉','苹果','鲤鱼','鳗鱼','任性的','细心的','粗心的','大意的','甜甜的','酷酷的','健壮的','英俊的','霸气的','阳光的','默默的','大力的','孝顺的','忧虑的','着急的','紧张的','善良的','凶狠的','害怕的','重要的','危机的','欢喜的','欣慰的','满意的','跳跃的','诚心的','称心的','如意的','怡然的','娇气的','无奈的','无语的','激动的','愤怒的','美好的','感动的','激情的','激昂的','震动的','虚拟的','超级的','寒冷的','精明的','明理的','犹豫的','忧郁的','寂寞的','奋斗的','勤奋的','现代的','过时的','稳重的','热情的','含蓄的','开放的','无辜的','多情的','纯真的','拉长的','热心的','从容的','体贴的','风中的','曾经的','追寻的','儒雅的','优雅的','开朗的','外向的','内向的','清爽的','文艺的','长情的','平常的','单身的','伶俐的','高大的','懦弱的','柔弱的','爱笑的','乐观的','耍酷的','酷炫的','神勇的','年轻的','唠叨的','瘦瘦的','无情的','包容的','顺心的','畅快的','舒适的','靓丽的','负责的','背后的','简单的','谦让的','彩色的','缥缈的','欢呼的','生动的','复杂的','慈祥的','仁爱的','魔幻的','虚幻的','淡然的','受伤的','雪白的','高高的','糟糕的','顺利的','闪闪的','羞涩的','缓慢的','迅速的','优秀的','聪明的','含糊的','俏皮的','淡淡的','坚强的','平淡的','欣喜的','能干的','灵巧的','友好的','机智的','机灵的','正直的','谨慎的','俭朴的','殷勤的','虚心的','辛勤的','自觉的','无私的','无限的','踏实的','老实的','现实的','可靠的','务实的','拼搏的','个性的','粗犷的','活力的','成就的','勤劳的','单纯的','落寞的','朴素的','悲凉的','忧心的','洁净的','清秀的','自由的','小巧的','单薄的','贪玩的','刻苦的','干净的','壮观的','和谐的','文静的','调皮的','害羞的','安详的','自信的','端庄的','坚定的','美满的','舒心的','温暖的','专注的','勤恳的','美丽的','腼腆的','优美的','甜美的','甜蜜的','整齐的','动人的','典雅的','尊敬的','舒服的','妩媚的','秀丽的','喜悦的','甜美的','彪壮的','强健的','大方的','俊秀的','聪慧的','迷人的','陶醉的','悦耳的','动听的','明亮的','结实的','魁梧的','标致的','清脆的','敏感的','光亮的','大气的','老迟到的','知性的','冷傲的','呆萌的','野性的','隐形的','笑点低的','微笑的','笨笨的','难过的','沉静的','火星上的','失眠的','安静的','纯情的','要减肥的','迷路的','烂漫的','哭泣的','贤惠的','苗条的','温婉的','发嗲的','会撒娇的','贪玩的','执着的','眯眯眼的','花痴的','想人陪的','眼睛大的','高贵的','傲娇的','心灵美的','爱撒娇的','细腻的','天真的','怕黑的','感性的','飘逸的','怕孤独的','忐忑的','高挑的','傻傻的','冷艳的','爱听歌的','还单身的','怕孤单的','懵懂的');

    $nicheng_wei=array('嚓茶','凉面','便当','毛豆','花生','可乐','灯泡','哈密瓜','野狼','背包','眼神','缘分','雪碧','人生','牛排','蚂蚁','飞鸟','灰狼','斑马','汉堡','悟空','巨人','绿茶','自行车','保温杯','大碗','墨镜','魔镜','煎饼','月饼','月亮','星星','芝麻','啤酒','玫瑰','大叔','小伙','哈密瓜，数据线','太阳','树叶','芹菜','黄蜂','蜜粉','蜜蜂','信封','西装','外套','裙子','大象','猫咪','母鸡','路灯','蓝天','白云','星月','彩虹','微笑','摩托','板栗','高山','大地','大树','电灯胆','砖头','楼房','水池','鸡翅','蜻蜓','红牛','咖啡','机器猫','枕头','大船','诺言','钢笔','刺猬','天空','飞机','大炮','冬天','洋葱','春天','夏天','秋天','冬日','航空','毛衣','豌豆','黑米','玉米','眼睛','老鼠','白羊','帅哥','美女','季节','鲜花','服饰','裙子','白开水','秀发','大山','火车','汽车','歌曲','舞蹈','老师','导师','方盒','大米','麦片','水杯','水壶','手套','鞋子','自行车','鼠标','手机','电脑','书本','奇迹','身影','香烟','夕阳','台灯','宝贝','未来','皮带','钥匙','心锁','故事','花瓣','滑板','画笔','画板','学姐','店员','电源','饼干','宝马','过客','大白','时光','石头','钻石','河马','犀牛','西牛','绿草','抽屉','柜子','往事','寒风','路人','橘子','耳机','鸵鸟','朋友','苗条','铅笔','钢笔','硬币','热狗','大侠','御姐','萝莉','毛巾','期待','盼望','白昼','黑夜','大门','黑裤','钢铁侠','哑铃','板凳','枫叶','荷花','乌龟','仙人掌','衬衫','大神','草丛','早晨','心情','茉莉','流沙','蜗牛','战斗机','冥王星','猎豹','棒球','篮球','乐曲','电话','网络','世界','中心','鱼','鸡','狗','老虎','鸭子','雨','羽毛','翅膀','外套','火','丝袜','书包','钢笔','冷风','八宝粥','烤鸡','大雁','音响','招牌','胡萝卜','冰棍','帽子','菠萝','蛋挞','香水','泥猴桃','吐司','溪流','黄豆','樱桃','小鸽子','小蝴蝶','爆米花','花卷','小鸭子','小海豚','日记本','小熊猫','小懒猪','小懒虫','荔枝','镜子','曲奇','金针菇','小松鼠','小虾米','酒窝','紫菜','金鱼','柚子','果汁','百褶裙','项链','帆布鞋','火龙果','奇异果','煎蛋','唇彩','小土豆','高跟鞋','戒指','雪糕','睫毛','铃铛','手链','香氛','红酒','月光','酸奶','银耳汤','咖啡豆','小蜜蜂','小蚂蚁','蜡烛','棉花糖','向日葵','水蜜桃','小蝴蝶','小刺猬','小丸子','指甲油','康乃馨','糖豆','薯片','口红','超短裙','乌冬面','冰淇淋','棒棒糖','长颈鹿','豆芽','发箍','发卡','发夹','发带','铃铛','小馒头','小笼包','小甜瓜','冬瓜','香菇','小兔子','含羞草','短靴','睫毛膏','小蘑菇','跳跳糖','小白菜','草莓','柠檬','月饼','百合','纸鹤','小天鹅','云朵','芒果','面包','海燕','小猫咪','龙猫','唇膏','鞋垫','羊','黑猫','白猫','万宝路','金毛','山水','音响');

    $tou_num=rand(0,331);

    $wei_num=rand(0,325);

    $nicheng=$nicheng_tou[$tou_num].$nicheng_wei[$wei_num];

    return $nicheng;
}


/**
 * 空列表
 * @return array
 */
function getEmptyList(){
    return [
        'total' => 0,
        'per_page' => 0,
        'current_page' => 0,
        'last_page' => 0,
        'data' => []
    ];
}

/**
* 生成流水号
*/
function serialNumber(){
    return date("YmdHis").uniqid();
}


function RemoveXSS($val) {  
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed  
   // this prevents some character re-spacing such as <java\0script>  
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs  
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);  

   // straight replacements, the user should never need these since they're normal characters  
   // this prevents like <IMG SRC=@avascript:alert('XSS')>  
   $search = 'abcdefghijklmnopqrstuvwxyz'; 
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';  
   $search .= '1234567890!@#$%^&*()'; 
   $search .= '~`";:?+/={}[]-_|\'\\'; 
   for ($i = 0; $i < strlen($search); $i++) { 
      // ;? matches the ;, which is optional 
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars 

      // @ @ search for the hex values 
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ; 
      // @ @ 0{0,7} matches '0' zero to seven times  
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; 
   } 

   // now the only remaining whitespace attacks are \t, \n, and \r 
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'); 
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); 
   $ra = array_merge($ra1, $ra2); 

   $found = true; // keep replacing as long as the previous round replaced something 
   while ($found == true) { 
      $val_before = $val; 
      for ($i = 0; $i < sizeof($ra); $i++) { 
         $pattern = '/'; 
         for ($j = 0; $j < strlen($ra[$i]); $j++) { 
            if ($j > 0) { 
               $pattern .= '(';  
               $pattern .= '(&#[xX]0{0,8}([9ab]);)'; 
               $pattern .= '|';  
               $pattern .= '|(&#0{0,8}([9|10|13]);)'; 
               $pattern .= ')*'; 
            } 
            $pattern .= $ra[$i][$j]; 
         } 
         $pattern .= '/i';  
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag  
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags  
         if ($val_before == $val) {  
            // no replacements were made, so exit the loop  
            $found = false;  
         }  
      }  
   }  
   return $val;  
}   



/**
* 转义 XSS过滤
*/
function filterXss($val){
    $val = str_replace(' ', '', $val);
    $val = addslashes($val);
    $val = str_replace('%', '\%', $val);
    return htmlspecialchars($val);
}

//主动判断是否HTTPS
function isHttps()
{
    //var_dump($_SERVER['SERVER_PORT']);die;
    if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
        return true;
    } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return true;
    }
    return false;
}

/**
* 生成完整图片地址
*/
function getImage($image){
    $host = $_SERVER['HTTP_HOST'];
    if(!preg_match('/^(http|https)/', $image)){
        //var_dump(isHttps());die;
        if(isHttps()){
            return "https://".$host.$image;
        }else{
            
            return "https://".$host.$image;
        }
    }
    //$image = str_replace("http://", "https://", $image);
    return $image;
}